var param = {}, formId = 'queryForm', url = "/openx/boss/channelGoodsService/listChannelGoodsByPage", isInit = false;

//初始化表格
(function () {
	$(".chosen-select-no-single").chosen({disable_search_threshold: 10});

	var data = $.openx.getJsonObj(formId);
	//取个随机数查询，使第一次查询为空
	data.channelCodes = 'fdsfasxxx56236589' + '-' + new Date().getTime();
	param.channelGoods = data;
	$.openx.initTable("table", url, param);
    $("#channelCode, #channelCodeImport").yfChannel({
        url: ecp_boss_server + '/openx/boss/channelService/listChannelTree',
        filter: 'leaves'
    });
})();

function activityTimeFormat(value, row){
    
    var beginTime = row.activityBeginTime;
    var endTime = row.activityEndTime;
    if(beginTime == undefined || endTime == undefined){
        return "-";
    }

    return $.openx.formatDate(new Date(beginTime), "yyyy-MM-dd hh:mm:ss")+" - "+$.openx.formatDate(new Date(endTime), "yyyy-MM-dd hh:mm:ss"); 
}


//格式化订单详情按钮
function showControllFormat(value, row) {
	var statusName, status;
	
	var s = "<a href=\'javascript:void(0)\' onclick =\"javascript:showEditWindow('" + row.channelCode + "','" + row.goodsCode + "')\"><button type='button' class='btn btn-outline btn-primary btn-xs'>编辑</button> </a>";
	return s;
}

//初始化时间
layui.use('laydate', function () {
	
	 var laydate = layui.laydate;
	 document.getElementById('activityBeginTime').value = laydate.now() + ' 00:00:00';
	 document.getElementById('activityEndTime').value = laydate.now() + ' 23:59:59';
 
	 var data = $.openx.getJsonObj(formId);
	 param.channelGoods = data;
	 //$.openx.initTable("table", url, param);
 });


function showFormatStatus(value, row) {
	var statusName, status;
	if(row.status == "OFF_LINE") {
		statusName = '下架';
	} else {
		statusName = '上架';
	}
	return statusName;
}

function showImportExcel() {
	$("#excelFileInput").val("");
	$("#import-form").modal("show");
	$("#channelCodeImport").yfChannel("reset");
	$("#uploadImgResult").hide();
	$('#importAll').hide();	
	$('#prompt').hide();
	$('#goBack').hide();
	$('#cancerModel').show();	
	$('#importExcelButton').show();
	$('#channelCodeImport').attr("disabled",false);
	$('#excelFileInput').attr("disabled",false);
	$('#importExcelButton').attr("disabled",false);
}


function resetForm() {
	$('#queryForm')[0].reset();
	
    // $.openx.query();
	$("#channelCode").yfChannel("reset");
	var laydate = layui.laydate;
    console.log(laydate.now().split(' ')[0]);
    document.getElementById('activityBeginTime').value = laydate.now().split(' ')[0] + ' 00:00:00';
    document.getElementById('activityEndTime').value = laydate.now().split(' ')[0] + ' 23:59:59';

    // var data = $.openx.getJsonObj(formId);
    // param.channelGoods = data;
    // $.openx.initTable("table", url, param);
	
}


function showEditWindow(channelCode, goodsCode) {
	$X("/boss/channelGoodsService", "getChannelGoodsDetail").callx({
		channelCode : channelCode,
		goodsCode : goodsCode,
        onResult: function (result) {
        	console.log(result);
			var html = $.openx.innerHtml('editFormTemplate');
			if(result.activityBeginTime && result.activityEndTime){
				result.activityBeginTime = $.openx.formatDate(new Date(result.activityBeginTime), "yyyy-MM-dd hh:mm:ss");
				result.activityEndTime = $.openx.formatDate(new Date(result.activityEndTime), "yyyy-MM-dd hh:mm:ss");
			}
			console.log(result);
        	laytpl($.openx.innerHtml('editFormTemplate')).render(result, function (html) {
				
                $.openx.openLayer('[auto, 700]', '编辑活动商品', html, true, function() {
                	validatorForm();
                	if($("#editForm").valid()) {
                		saveActivityGoods();
                	}
                });
            });
        },
        onError: function (error) {
        }
    });
}

function validatorForm() {
	$("#editForm").validate({
		rules: {
			activityBeginTime: {
		      required: true,
		    },
		    activityEndTime : {
		    	required : true,
		    },
		    activityPrice :  {
		    	required : true,
				number : true,
				min:0.01
		    }

		    // goodsMark : "required"
		  }
	});
}

function saveActivityGoods() {
	var data = $.openx.getJsonObj('editForm');
	$X("/boss/channelGoodsService", "updateActivityGoods").callx({
		channelGoods : data,
        onResult: function (result) {
			if(result && result.length > 0){
				$('#updateResult').html(result);
			}else{
				layer.closeAll();
				refreshTable();
			}
        	
        },
        onError: function (error) {
        }
    });
}

function search() {
	if(!isInit) {
		isInit = true;
		
	}
	var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length == 0) {
    	layer.msg("请选择渠道！");
    	return ;
    }
	refreshTable();
}

function refreshTable() {
	var channelCode = [];
	var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length > 0) {
        $.each(channelList_data, function (i,item){
        	channelCode.push(item.displayChannel);
        });
    }
	$("#channelCodes").val(channelCode.join(","));
	var data = $.openx.getJsonObj(formId);
	param.channelGoods = data;
	$.openx.tableRefresh(url, param, true);
}

function importExcel(){	
	var importChannelCodeList = [];
    var channelList_data = $("#channelCodeImport").yfChannel("getData");
    if (channelList_data.length > 0) {
         $.each(channelList_data, function (i,item){
       	  importChannelCodeList.push(item.displayChannel);
         });
    };
	if(importChannelCodeList == ''){
		layer.tips("请选择渠道","#channelCodeImport",{
			tips:[2,"#f40"]
		})
		 return;
	}
	//判断文件大小
	checkFileSizeType('excelFileInput', 5*1024*1024, '');
	
	loadFileDataToBase64String('excelFileInput',function(excel){ 
		$("#importExcelButton").attr("disabled", true);
				
		$X("/boss/channelGoodsService", "importActivityExcel").callx({
			channelCodes : importChannelCodeList,
			base64Str : excel,
			warnMessage:"",
			onResult : function(data) {
				$("#importExcelButton").attr("disabled", false);
				if(data && data.length > 0) { 
					if(data[0] == 'price'){
						data[0] = '';
						var resultStr = "";
						for(var i=1;i<data.length;i++){
							resultStr = resultStr+data[i]+"\n";
							
						}
						console.log(resultStr);
						$('#uploadImgResult').val(resultStr);
						$('#uploadImgResult').show();
						$('#prompt').show();
						$('#prompt').html('商品价格预警，是否仍全部导入。');
						$('#importAll').show();	
						$('#goBack').show();	
						$('#cancerModel').hide();
						$('#importExcelButton').hide();
						$('#channelCodeImport').attr("disabled",true);
						$('#excelFileInput').attr("disabled",true);
					}else if(data[0] == 'params'){
						data[0] = '';
						var resultStr = "";
						for(var i=1;i<data.length;i++){
							resultStr = resultStr+data[i]+"\n";
							
						}
						$('#uploadImgResult').val(resultStr);
						$('#uploadImgResult').show();
					}
					//$('#uploadImgResult').html(data);
				} else {
					$('#prompt').html("已加入导入队列!!!");
				}
           },
           //请求失败执行
           onError : function(error) {
        	   $("#importExcelButton").attr("disabled", false);
               var res = JSON.parse(error);
               $('#uploadImgResult').html(res.message);
               layer.msg(res.message)
           }
       }, 3000*1000);
	});    	
}

function goBack(){
	$('#prompt').hide();
	$('#importAll').hide();	
	$('#goBack').hide();	
	$('#cancerModel').show();
	$('#importExcelButton').show();
	$('#uploadImgResult').hide();
	$('#uploadImgResult').val('');
	$('#channelCodeImport').attr("disabled",false);
	$('#excelFileInput').attr("disabled",false);
	$("#importExcelButton").attr("disabled", false);
}

function importAll(){
	var importChannelCodeList = [];
	var channelList_data = $("#channelCodeImport").yfChannel("getData");
	$.each(channelList_data, function (i,item){
		importChannelCodeList.push(item.displayChannel);
	});
	loadFileDataToBase64String('excelFileInput',function(excel){ 
		$("#importExcelButton").attr("disabled", true);
				
		$X("/boss/channelGoodsService", "importActivityExcel").callx({
			channelCodes : importChannelCodeList,
			base64Str : excel,
			warnMessage:$('#uploadImgResult').val(),
			onResult : function(data) {
				$('#prompt').html('已加入导入队列!!!');
				$('#uploadImgResult').val('');
				$('#uploadImgResult').hide();
	   },
	   //请求失败执行
	   onError : function(error) {
		   $("#importExcelButton").attr("disabled", false);
		   var res = JSON.parse(error);
		   $('#uploadImgResult').html(res.message);
		   layer.msg(res.message)
	   }
	}, 3000*1000);
	});    	
}

//检查文件大小和扩展名
function checkFileSizeType(fileId, maxFileSize, fileTypeArr) {
    var file = document.getElementById(fileId).files[0];
    if (!file) {
    	layer.tips("请选择文件！","#excelFileInput",{
			tips:[2,"#f40"]
		})
        return -1;
    }
    //检查文件类型
    if (fileTypeArr && fileTypeArr.length > 0) {
        for (var i = 0; i < fileTypeArr.length; i++) {
            fileTypeArr[i] = fileTypeArr[i].toLowerCase();
        }
        if (fileTypeArr.indexOf(file.name.substring(file.name.lastIndexOf("."), file.name.length).toLowerCase()) === -1) {
            layer.tips("上传文件类型错误！","#excelFileInput",{
    			tips:[2,"#f40"]
    		})
    		return -1;
        }
    }
    //检查文件大小
    if (file.size > maxFileSize) {
        layer.tips("上传文件不能大于" + (maxFileSize / 1024 ).toFixed(2) + "KB！","#excelFileInput",{
			tips:[2,"#f40"]
		})
		return -1;
    }
}

function loadFileDataToBase64String(fileName, callback) {
	var file = document.getElementById(fileName).files[0];
    //读取文件
    var reader = new FileReader();
    reader.onload = function () {
        var result = this.result.split('base64,')[1];
        callback(result);
    }
    reader.readAsDataURL(file);
}


function getActivityDetail(){

}